package br.com.biovida;

import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class Util {

	public static final String STRING_VAZIA = "";

	public static final String LISTA_PESSOA_JURIDICA_SESSION = "listaPessoaJuridica";
	public static final String LISTA_RESPONSAVEL_TECNICO_SESSION = "listaResponsavelTecnico";

	public static Boolean isNull(Object objeto) {
		return (objeto == null) ? Boolean.TRUE : Boolean.FALSE;
	}

	public static Boolean isEmptyString(String str) {
		return (!Util.isNull(str) && str.length() == 0) ? Boolean.TRUE : Boolean.FALSE;
	}

	@SuppressWarnings("rawtypes")
	public static boolean isNullOuVazio(Object pObjeto) {

		if (pObjeto == null) {

			return true;
		} else if (pObjeto instanceof Collection) {

			return ((Collection) pObjeto).isEmpty();
		} else if (pObjeto instanceof String) {

			return ((String) pObjeto).trim().equals(STRING_VAZIA);
		} else if (pObjeto instanceof Integer) {

			return ((Integer) pObjeto).intValue() == 0;
		}

		return false;
	}

	public static String formatarNumero(String pValor) {

		String lNumeroFormatado = "";

		if (!isNullOuVazio(pValor.trim())) {

			for (int lIndice = 0; lIndice < pValor.length(); lIndice++) {

				if (Character.isDigit(pValor.charAt(lIndice)) || pValor.charAt(lIndice) == ',' || pValor.charAt(lIndice) == '.') {

					lNumeroFormatado = lNumeroFormatado + pValor.charAt(lIndice);
				}
			}
		}

		return lNumeroFormatado;
	}

	public static boolean validaEmail(String pEmail) {

		boolean lValidade = false;

		String lEr = "[a-zA-Z]+[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]*\\.+[a-zA-Z]{2,4}";

		Pattern lPattern = Pattern.compile(lEr);
		Matcher lMatcher = lPattern.matcher(pEmail.trim());

		if (!isNullOuVazio(pEmail.trim()) && lMatcher.find() && lMatcher.group().equals(pEmail.trim()))
			lValidade = true;

		return lValidade;
	}

	public static HttpSession getSession() {
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		HttpSession session = request.getSession();
		return session;
	}

	public static void updateAttributeSession(String attributeId, Object attribute) {
		getSession().setAttribute(attributeId, attribute);
	}

	public static Object getAttributeSession(String attributeId) {
		return getSession().getAttribute(attributeId);
	}

	/*public static <T> DataModel<T> castListToDataModel(Collection lista) {
		return new ListDataModel((List<T>) lista);
	}*/

	/*public static <T> DualListModel<T> castListToDualListModel(Collection pLista1, Collection pLista2) {
		return new DualListModel((List<T>) pLista1, (List<T>) pLista2);
	}*/

	public static <T> Boolean isObjectInList(T objeto, @SuppressWarnings("rawtypes") Collection lista) {
		Boolean retorno = Boolean.FALSE;
		if (lista != null) {
			for (Object t : lista) {
				if (t.equals(objeto)) {
					retorno = Boolean.TRUE;
				}
			}
		}
		return retorno;
	}

	public static boolean validaPeriodo(final Date pDate1, final Date pDate2) {

		if (Util.isNullOuVazio(pDate1) && Util.isNullOuVazio(pDate2)) {
			return true;
		}
		if (Util.isNullOuVazio(pDate1) && !Util.isNullOuVazio(pDate2) || !Util.isNullOuVazio(pDate1) && Util.isNullOuVazio(pDate2)) {
			return false;
		}
		if ((pDate1.compareTo(pDate2) > 0)) {
			return false;
		}

		return true;
	}

	/**
	 * Padds the string to the left with the given character for the specified
	 * length.
	 * 
	 * @param input
	 *            The input string.
	 * @param padding
	 *            The char used for padding.
	 * @param length
	 *            The length of the new string.
	 * @return The padded string.
	 */
	public static String lpad(String input, char padding, int length) {

		if (input == null) {
			input = new String();
		}

		if (input.length() >= length) {
			return input;
		} else {
			StringBuffer result = new StringBuffer();
			int numChars = length - input.length();
			for (int i = 0; i < numChars; i++) {
				result.append(padding);
			}
			result.append(input);
			return result.toString();
		}
	}

	public static String zeroLTrim(String substring) {
		if (!substring.isEmpty() && substring.length() > 1) {
			while (substring.startsWith("0")) {
				substring = substring.substring(1, substring.length());
			}
		}
		return substring;
	}

	public static String toMD5(String password) throws Exception {
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		BigInteger hash = new BigInteger(1, messageDigest.digest(password.getBytes()));
		return hash.toString(16);
	}

	public static String getImageFilePath(String nome) {
		String fileName = "imagens/" + nome + ".png";
		File file = new File(fileName);
		fileName = file.getAbsolutePath();
		if (file.exists()) {
			System.out.println("Using: " + fileName);
			return fileName;
		} else {
			System.out.println("File: " + fileName + " not Found!");
			fileName = "imagens/" + nome + ".png";
			file = new File(fileName);
			fileName = file.getAbsolutePath();
			if (file.exists()) {
				System.out.println("Using: " + fileName);
				return fileName;
			} else {
				System.out.println("File: " + fileName + " not Found!");
			}
		}
		return null;
	}

	public static enum enumStringContexto {
		PESSOA, EMPREENDIMENTO
	}

	public static String getReportFilePath(String nome) {
		String fileName = "reports/sources/";
		File file = new File(fileName);
		fileName = file.getAbsolutePath();
		if (file.exists()) {
			System.out.println("Using: " + fileName);
			return fileName;
		} else {
			System.out.println("File: " + fileName + " not Found!");
			fileName = "reports/sources/";
			file = new File(fileName);
			fileName = file.getAbsolutePath();
			if (file.exists()) {
				System.out.println("Using: " + fileName);
				return fileName;
			} else {
				System.out.println("File: " + fileName + " not Found!");
			}
		}
		return null;
	}

	/**
	 * Converte Grau com minuto e segundo para um valor decimal.
	 * 
	 * @param grau
	 * @param min
	 * @param seg
	 * @return A string
	 */
	public static String converterGrauEmDecimo(Integer grau, Integer min, Double seg) {
		Double frac = (min + seg / 60.0) / 60.0;
		Double decimal = -(grau + frac);
		NumberFormat formatter = new DecimalFormat("#0.000000");
		return formatter.format(decimal);
	}
	
	public static Boolean assertEquals(Object object, Object expected) {
		if (isNullOuVazio(object) && !isNullOuVazio(expected)) {
			return false;
		}

		if (object == expected) {
			return true;
		} else {
			return false;
		}

	}

	public static Collection<Integer> stringToArrayInt(String valor) {
		StringTokenizer token = new StringTokenizer(valor, ",");
		Collection<Integer> ides = new ArrayList<Integer>();
		while (token.hasMoreElements()) {
			ides.add(Integer.valueOf(token.nextToken()));
		}
		return ides;
	}
	
	public static String arrayIntToString(List<Integer> ides) {
		StringBuffer valor = new StringBuffer();
		
		int limite = ides.size() -1;
		for (int i = 0; i < ides.size(); i++) {
			Integer id = ides.get(i);
			if(i != limite) 
				valor.append(id+",");
			else 
				valor.append(id); 
		}
		
		return valor.toString();
	}

}